package views;

import helper.ColumnConfig;
import helper.TableModelHelper;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.xml.bind.ValidationException;

import utils.MessageBox;
import utils.StringUtil;
import controller.AdministradorProductos;
import controller.AdministradorSucursales;
import dto.AreaDTO;
import dto.ProductoDTO;
import dto.SucursalDTO;

public class ConsultarProductosPorVencer extends JFrame {
	
	private static final long serialVersionUID = -965569699815732723L;
	
	protected Container contentPane;
	private Vector<String> columnNames;
	private List<ColumnConfig> columns;
	private Vector<Vector<String>> rows;
	
	private JTable table;
	private TableModelHelper tableModel;
	private JScrollPane scrollPane;
	
	private JComboBox<SucursalDTO> cmbSucursal;
	private JComboBox<AreaDTO> cmbArea;
	private JTextField txtDias;
	
	
	public ConsultarProductosPorVencer() {
		this.setSize(700, 400);
		this.setTitle("Consultar Productos por Vencer");
		this.columnNames = new Vector<String>();
		this.columns = new ArrayList<ColumnConfig>();
		initGUI();
		loadData();
		addListeners();
	}

	private void initGUI() {
		centered();
		contentPane = getContentPane();
		contentPane.setLayout(new BorderLayout());
		JPanel panel = new JPanel();
		panel.setLayout(null);
		panel.setPreferredSize(new Dimension(700, 100));
		
		//Toolbar
//		JToolBar toolBar = new JToolBar();
//		addButtons(toolBar);
//	    add(toolBar, BorderLayout.NORTH);

	    JLabel lblSep = new JLabel("Parametros de consulta");		
		JSeparator separator = new JSeparator();
		lblSep.setBounds(15, 15, getWidth()-40, 20);
		separator.setBounds(10, 35, getWidth()-40, 20);
		panel.add(lblSep);
		panel.add(separator);
		
		// Sucursal
		JLabel lblSucursal = new JLabel("Sucursal");
		lblSucursal.setBounds(50, 70, 110, 25);
		panel.add(lblSucursal);
		cmbSucursal = new JComboBox();
		cmbSucursal.setBounds(120, 70, 120, 25);
		panel.add(cmbSucursal);
		
		// Area
		JLabel lblArea = new JLabel("Area");
		lblArea.setBounds(260, 70, 110, 25);
		panel.add(lblArea);
		cmbArea = new JComboBox();
		cmbArea.setBounds(300, 70, 120, 25);
		panel.add(cmbArea);
		
		// Dias
		JLabel lblDias = new JLabel("Rango dias");
		lblDias.setBounds(440, 70, 110, 25);
		panel.add(lblDias);
		txtDias = new JTextField();
		txtDias.setBounds(520, 70, 120, 25);
		panel.add(txtDias);
		
		// Buscar
		JButton btnFind = createButton("Buscar");
		btnFind.setBounds(120, 115, 120, 25);
	    btnFind.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				refreshTable();
			}
		});
	    panel.add(btnFind);
		
		add(panel, BorderLayout.CENTER);
		
		//Tabla
		columns.add(new ColumnConfig("idProducto", "ID"));
		columns.add(new ColumnConfig("nombre", "Producto"));
	    for (ColumnConfig columnConfig : columns) {
			columnNames.add(columnConfig.getLabel());
		}
	    
	    rows = new Vector<Vector<String>>();
	    tableModel = new TableModelHelper(columns);
	    tableModel.setDataVector(rows, columnNames);
	    table = new JTable(tableModel);
	    scrollPane = new JScrollPane(table);
	    scrollPane.setPreferredSize(new Dimension(660, 200));
	    add(scrollPane, BorderLayout.SOUTH);
	}
	
	private void loadData() {
		try {
			// Sucursales
			cmbSucursal.removeAllItems();
			List<SucursalDTO> sucursales = AdministradorSucursales.getInstance().getSucursalesDTO();
			for (SucursalDTO s : sucursales) {
				cmbSucursal.addItem(s);
			}
			
			// Areas
			cmbArea.removeAllItems();
			for (AreaDTO a : sucursales.get(0).getAreas()) {
				cmbArea.addItem(a);
			}
		} catch (RemoteException | ValidationException e) {
			e.printStackTrace();
		}
	}
	
	private void refreshTable() {
		// Valido datos
		if (validation()) {
			rows.clear();
			// Obtengo parametros
			AreaDTO areaDTO = (AreaDTO) cmbArea.getSelectedItem();
			int rangoDias = StringUtil.null2Integer(txtDias.getText());

			try {
				List<ProductoDTO> productos = AdministradorProductos.getInstance().productosPorVencer(areaDTO, rangoDias);
				for (ProductoDTO productoDTO : productos) {
					Vector<String> data = new Vector<String>();
					data.add(StringUtil.null2String(productoDTO.getId()));
					data.add(productoDTO.getNombre());
					rows.add(data);
				}
				
				// Armo tabla nuevamente
				contentPane.remove(scrollPane);
				tableModel = new TableModelHelper(columns);
			    tableModel.setDataVector(rows, columnNames);
			    table = new JTable(tableModel);
			    scrollPane = new JScrollPane(table);
			    scrollPane.setPreferredSize(new Dimension(660, 200));
			    add(scrollPane, BorderLayout.SOUTH);
			    contentPane.doLayout();
			} catch (Exception e) {
				MessageBox.Error("Error", "Surgio un error obteniendo los productos.");
			}
		}
	}
	
	private void addListeners() {
		// Sucursales
		cmbSucursal.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// Cargo areas
				cmbArea.removeAllItems();
				for (AreaDTO a : ((SucursalDTO)cmbSucursal.getSelectedItem()).getAreas()) {
					cmbArea.addItem(a);
				}
			}
		});
	}
	
	//Crea los botones por default
	private JButton createButton(String text) {
		JButton button = new JButton();
		button.setText(text);
		button.setToolTipText(text);
		button.setFocusPainted(false);
		return button;
	}
	
	//Validar Cosecha
	private boolean validation() {
		try {
			// Rango dias
			int rangoDias = StringUtil.null2Integer(txtDias.getText());
			if (rangoDias <= 0) {
				MessageBox.Error("Error", "El Rango de dias debe ser mayor a cero.");
				return false;
			}
			return true;
		} catch (Exception e) {
			MessageBox.Error("Error", "Rango de dias invalido.");
			return false;
		}
	}
	
	//Centra la ventana en medio de la pantalla
	private void centered() {
		Toolkit tk = Toolkit.getDefaultToolkit();
		Dimension screenSize = tk.getScreenSize();
	    int screenHeight = screenSize.height;
	    int screenWidth = screenSize.width;
	    setLocation(screenWidth / 4, screenHeight / 4);
	}
	
	public static void main(String[] args) {
		ConsultarProductosPorVencer c = new ConsultarProductosPorVencer();
		c.setVisible(true);
	}

}
